<template>
  <div class="comment-container">
    <!-- 评论列表 -->
    <div class="comment-list">
      <div v-for="comment in currentPageComments" :key="comment.id" class="comment-item">
        <!-- 根评论 -->
        <div class="comment-root">
          <n-avatar round :size="40" :src="comment.avatar || '/placeholder.jpg'" />
          <div class="comment-content">
            <div class="comment-header">
              <span class="username">{{ comment.userName }}</span>
              <span class="time">{{ formatDate(comment.createdTime) }}</span>
            </div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-actions">
              <span class="action-btn" @click="handleReply(comment)">回复</span>
              <div class="like-btn">
                <span>{{ comment.likeCount || 0 }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 所有回复（扁平化显示） -->
        <div class="reply-list" v-if="comment.replies && comment.replies.length > 0">
          <div
            v-for="reply in comment.replies"
            :key="reply.id"
            class="reply-item"
          >
            <n-avatar round :size="36" :src="reply.avatar || '/placeholder.jpg'" />
            <div class="reply-content">
              <div class="reply-header">
                <span class="username">{{ reply.userName }}</span>
                <span class="time">{{ formatDate(reply.createdTime) }}</span>
              </div>
              <div class="reply-text">
                <!-- 只有回复其他回复的评论才显示"回复@用户名" -->
                <template v-if="reply.parentId !== comment.id && reply.toName">
                  回复 <span class="reply-to">@{{ reply.toName }}</span>：{{ reply.content }}
                </template>
                <template v-else>
                  {{ reply.content }}
                </template>
              </div>
              <div class="reply-actions">
                <span class="action-btn" @click="handleReply(reply)">回复</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <n-pagination
        v-model:page="currentPage"
        :page-count="totalPages"
        :page-size="pageSize"
        :item-count="commentList.length"
        show-size-picker
        :page-sizes="[5, 10, 20]"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </div>

    <!-- 回复框 -->
    <div class="reply-box" v-if="showReplyBox">
      <n-avatar round :size="36" src="/placeholder.jpg" />
      <div class="reply-input-wrapper">
        <n-input
          v-model:value="replyContent"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 3 }"
          :placeholder="replyPlaceholder"
        />
        <div class="reply-actions-bar">
          <n-button type="primary" size="small" :disabled="!replyContent" @click="submitReply">
            发布
          </n-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { NAvatar, NButton, NInput, NPagination } from 'naive-ui'

// 定义原始评论数据类型
interface CommentNode {
  rootNode: boolean
  leafNode: boolean
  children?: CommentNode[]
  id: number
  momentId: number
  replyType: number // 1: 评论, 2: 回复
  content: string
  fromId?: string
  toId?: string
  toName?: string
  toAvatar?: string
  parentId: number
  userName: string
  avatar: string
  createdTime: number
  nodeId: number
  nodePId: number
  likeCount?: number
}

// 定义扁平化后的评论数据类型
interface FlatComment {
  id: number
  momentId: number
  replyType: number
  content: string
  fromId?: string
  toId?: string
  toName?: string
  toAvatar?: string
  parentId: number
  userName: string
  avatar: string
  createdTime: number
  nodeId: number
  nodePId: number
  likeCount?: number
  replies: FlatReply[] // 所有回复都在这一层
}

// 定义扁平化后的回复数据类型
interface FlatReply {
  id: number
  momentId: number
  replyType: number
  content: string
  fromId?: string
  toId?: string
  toName?: string
  toAvatar?: string
  parentId: number // 这个字段用来判断是否是直接回复根评论
  userName: string
  avatar: string
  createdTime: number
  nodeId: number
  nodePId: number
  likeCount?: number
  rootCommentId: number // 添加根评论ID，用于关联
}

// 原始嵌套数据
const originalCommentList = ref<CommentNode[]>([
  {
    "rootNode": true,
    "leafNode": false,
    "children": [
      {
        "rootNode": false,
        "leafNode": false,
        "children": [
          {
            "rootNode": false,
            "leafNode": false,
            "children": [
              {
                "rootNode": false,
                "leafNode": true,
                "id": 14,
                "momentId": 2,
                "replyType": 2,
                "content": "我不信",
                "fromId": "oYA4Ht-ccqtFw0UtHAeQzGfXNaZs",
                "toId": "oYA4HtwGJEsLio6pGrhx5Hzv9XD0",
                "toName": "鸡翅老鸽",
                "toAvatar": "/placeholder.jpg",
                "parentId": 12,
                "userName": "鸡翅粉丝",
                "avatar": "/placeholder.jpg",
                "createdTime": 1733154508000,
                "nodeId": 14,
                "nodePId": 12,
                "likeCount": 2
              }
            ],
            "id": 12,
            "momentId": 2,
            "replyType": 2,
            "content": "我也信了",
            "fromId": "oYA4HtwGJEsLio6pGrhx5Hzv9XD0",
            "toId": "oYA4Ht0LYVOCcwevzlImKZHpFSiE",
            "toName": "鸡腿哥",
            "toAvatar": "/placeholder.jpg",
            "parentId": 11,
            "userName": "鸡翅老鸽",
            "avatar": "/placeholder.jpg",
            "createdTime": 1732778561000,
            "nodeId": 12,
            "nodePId": 11,
            "likeCount": 12
          }
        ],
        "id": 11,
        "momentId": 2,
        "replyType": 2,
        "content": "我信啊",
        "fromId": "oYA4Ht0LYVOCcwevzlImKZHpFSiE",
        "toId": "oYA4Ht0LYVOCcwevzlImKZHpFSiE",
        "toName": "鸡腿哥",
        "toAvatar": "/placeholder.jpg",
        "parentId": 10,
        "userName": "鸡腿哥",
        "avatar": "/placeholder.jpg",
        "createdTime": 1732778524000,
        "nodeId": 11,
        "nodePId": 10,
        "likeCount": 27
      }
    ],
    "id": 10,
    "momentId": 2,
    "replyType": 1,
    "content": "我不信哈哈哈",
    "toName": "鸡腿哥",
    "toAvatar": "/placeholder.jpg",
    "parentId": -1,
    "userName": "鸡腿哥",
    "avatar": "/placeholder.jpg",
    "createdTime": 1732778517000,
    "nodeId": 10,
    "nodePId": -1,
    "likeCount": 56
  },
  {
    "rootNode": true,
    "leafNode": false,
    "children": [
      {
        "rootNode": false,
        "leafNode": true,
        "id": 15,
        "momentId": 2,
        "replyType": 2,
        "content": "有什么可能",
        "fromId": "oYA4Ht-ccqtFw0UtHAeQzGfXNaZs",
        "toId": "oYA4Ht0j1NRLCDJ6KyTOgzXT2nMQ",
        "toName": "鸡哥的鸡",
        "toAvatar": "/placeholder.jpg",
        "parentId": 13,
        "userName": "鸡翅粉丝",
        "avatar": "/placeholder.jpg",
        "createdTime": 1733154674000,
        "nodeId": 15,
        "nodePId": 13,
        "likeCount": 22
      }
    ],
    "id": 13,
    "momentId": 2,
    "replyType": 1,
    "content": "把k去掉倒是有可能",
    "toName": "鸡哥的鸡",
    "toAvatar": "/placeholder.jpg",
    "parentId": -1,
    "userName": "鸡哥的鸡",
    "avatar": "/placeholder.jpg",
    "createdTime": 1732945356000,
    "nodeId": 13,
    "nodePId": -1,
    "likeCount": 65
  }
])

// 扁平化评论数据
const flattenComments = (comments: CommentNode[]): FlatComment[] => {
  const result: FlatComment[] = []

  comments.forEach(comment => {
    if (comment.rootNode) {
      // 创建根评论
      const flatComment: FlatComment = {
        id: comment.id,
        momentId: comment.momentId,
        replyType: comment.replyType,
        content: comment.content,
        fromId: comment.fromId,
        toId: comment.toId,
        toName: comment.toName,
        toAvatar: comment.toAvatar,
        parentId: comment.parentId,
        userName: comment.userName,
        avatar: comment.avatar,
        createdTime: comment.createdTime,
        nodeId: comment.nodeId,
        nodePId: comment.nodePId,
        likeCount: comment.likeCount,
        replies: []
      }

      // 收集所有回复（递归收集所有层级的回复）
      const collectReplies = (node: CommentNode, rootId: number) => {
        if (node.children && node.children.length > 0) {
          node.children.forEach(child => {
            // 添加回复到扁平结构
            const flatReply: FlatReply = {
              id: child.id,
              momentId: child.momentId,
              replyType: child.replyType,
              content: child.content,
              fromId: child.fromId,
              toId: child.toId,
              toName: child.toName,
              toAvatar: child.toAvatar,
              parentId: child.parentId,
              userName: child.userName,
              avatar: child.avatar,
              createdTime: child.createdTime,
              nodeId: child.nodeId,
              nodePId: child.nodePId,
              likeCount: child.likeCount,
              rootCommentId: rootId
            }

            flatComment.replies.push(flatReply)

            // 递归处理子回复
            collectReplies(child, rootId)
          })
        }
      }

      collectReplies(comment, comment.id)

      // 按时间排序回复
      flatComment.replies.sort((a, b) => a.createdTime - b.createdTime)

      result.push(flatComment)
    }
  })

  return result
}

// 生成更多模拟数据用于分页测试
const generateMoreComments = () => {
  const moreComments: CommentNode[] = []

  for (let i = 0; i < 10; i++) {
    const rootComment: CommentNode = {
      rootNode: true,
      leafNode: false,
      id: 100 + i,
      momentId: 2,
      replyType: 1,
      content: `测试评论 ${i + 1}`,
      toName: "测试用户",
      toAvatar: "/placeholder.jpg",
      parentId: -1,
      userName: `测试用户 ${i + 1}`,
      avatar: "/placeholder.jpg",
      createdTime: Date.now() - i * 86400000, // 每条评论间隔一天
      nodeId: 100 + i,
      nodePId: -1,
      likeCount: Math.floor(Math.random() * 100),
      children: []
    }

    // 添加1-3条回复
    const replyCount = Math.floor(Math.random() * 3) + 1
    for (let j = 0; j < replyCount; j++) {
      const reply: CommentNode = {
        rootNode: false,
        leafNode: j === replyCount - 1,
        id: 1000 + i * 10 + j,
        momentId: 2,
        replyType: 2,
        content: `回复测试 ${j + 1}`,
        fromId: `user-${j}`,
        toId: `user-root-${i}`,
        toName: rootComment.userName,
        toAvatar: rootComment.avatar,
        parentId: rootComment.id,
        userName: `回复用户 ${j + 1}`,
        avatar: "/placeholder.jpg",
        createdTime: Date.now() - i * 86400000 - j * 3600000, // 每条回复间隔一小时
        nodeId: 1000 + i * 10 + j,
        nodePId: rootComment.id,
        likeCount: Math.floor(Math.random() * 50)
      }

      rootComment.children?.push(reply)
    }

    moreComments.push(rootComment)
  }

  return moreComments
}

// 扁平化后的评论列表
const commentList = ref<FlatComment[]>([])

// 初始化数据
onMounted(() => {
  // 添加更多测试数据
  const moreComments = generateMoreComments()
  const allComments = [...originalCommentList.value, ...moreComments]

  // 扁平化处理
  commentList.value = flattenComments(allComments)
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const totalPages = computed(() => Math.ceil(commentList.value.length / pageSize.value))
const currentPageComments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return commentList.value.slice(start, end)
})

// 回复相关状态
const showReplyBox = ref(false)
const replyContent = ref('')
const currentReplyTo = ref<FlatComment | FlatReply | null>(null)
const currentRootComment = ref<FlatComment | null>(null)
const replyPlaceholder = computed(() => {
  return currentReplyTo.value
    ? `回复 @${currentReplyTo.value.userName}：`
    : '写下你的评论...'
})

// 格式化日期为 YYYY-MM-DD 格式
const formatDate = (timestamp: number): string => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 处理回复
const handleReply = (target: FlatComment | FlatReply) => {
  showReplyBox.value = true
  currentReplyTo.value = target

  // 如果是回复根评论
  if ('replies' in target) {
    currentRootComment.value = target
  }
  // 如果是回复其他回复
  else {
    const rootComment = commentList.value.find(comment => comment.id === target.rootCommentId)
    currentRootComment.value = rootComment || null
  }

  replyContent.value = ''
}

// 提交回复
const submitReply = () => {
  if (!replyContent.value || !currentReplyTo.value || !currentRootComment.value) return

  // 创建新回复
  const newReply: FlatReply = {
    id: Date.now(),
    momentId: currentReplyTo.value.momentId,
    replyType: 2,
    content: replyContent.value,
    fromId: 'current-user-id', // 当前用户ID
    toId: currentReplyTo.value.fromId || currentReplyTo.value.id.toString(),
    toName: currentReplyTo.value.userName,
    toAvatar: currentReplyTo.value.avatar,
    parentId: currentReplyTo.value.id, // 保存父评论ID，用于判断是否显示"回复@用户名"
    userName: '当前用户', // 当前用户名称
    avatar: "/placeholder.jpg", // 当前用户头像
    createdTime: Date.now(),
    nodeId: Date.now(),
    nodePId: currentReplyTo.value.id,
    likeCount: 0,
    rootCommentId: currentRootComment.value.id
  }

  // 添加到根评论的回复列表
  currentRootComment.value.replies.push(newReply)

  // 按时间排序
  currentRootComment.value.replies.sort((a, b) => a.createdTime - b.createdTime)

  // 重置回复框
  replyContent.value = ''
  showReplyBox.value = false
  currentReplyTo.value = null
  currentRootComment.value = null
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
}

// 处理每页条数变化
const handlePageSizeChange = (pageSize: number) => {
  pageSize.value = pageSize
  // 当页数变化时，可能需要调整当前页码
  if (currentPage.value > totalPages.value) {
    currentPage.value = totalPages.value
  }
}
</script>

<style scoped>
.comment-container {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  max-width: 100%;
  margin: 0 auto;
  background-color: #fff;
}

.comment-list {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
}

.comment-item {
  display: flex;
  flex-direction: column;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-root {
  display: flex;
  gap: 12px;
  padding: 0 16px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.username {
  font-weight: 500;
  font-size: 14px;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 12px;
  word-break: break-word;
  color: #333;
}

.comment-actions {
  display: flex;
  gap: 24px;
}

.action-btn {
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.action-btn:hover {
  color: #1890ff;
}

.like-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 14px;
}

.reply-list {
  display: flex;
  flex-direction: column;
  margin-left: 52px;
  margin-top: 16px;
}

.reply-item {
  display: flex;
  gap: 12px;
  padding: 0 16px 16px 0;
  margin-bottom: 16px;
}

.reply-item:last-child {
  margin-bottom: 0;
}

.reply-content {
  flex: 1;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.reply-text {
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 12px;
  word-break: break-word;
  color: #333;
}

.reply-to {
  color: #1890ff;
  font-weight: 500;
}

.reply-actions {
  display: flex;
  gap: 24px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.reply-box {
  margin-top: 20px;
  display: flex;
  gap: 12px;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
}

.reply-input-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reply-actions-bar {
  display: flex;
  justify-content: flex-end;
}
</style>
